# The isBadVersion API is already defined for you.
# @param version, an integer
# @return an integer
# def isBadVersion(version):

class Solution:
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        left = 1
        right = n
        while left <= right:
            mid = (left+right) // 2
            # 如果是坏的
            if isBadVersion(mid):
                # 是第一个，则直接返回
                if mid == 1:
                    return mid
                # 不是第一个，但是上一个是好的，返回
                if not isBadVersion(mid-1):
                    return mid
                # 第一个坏的还在前面，修改right的值
                elif isBadVersion(mid-1):
                    right = mid - 1
            # 如果不是坏的，则第一个坏的在后面，修改left的值
            else:
                left = mid + 1